package runtime

import (
	"bytes"
	"github.com/allegro/bigcache"
	"runtime"
	"strconv"
	"time"
)

type Runtimes struct {
	localCache *bigcache.BigCache
}

func (r Runtimes) GetCache(name string, original func() string) string {
	var cache string
	byteCache, _ := r.localCache.Get(name)
	if len(byteCache) == 0 {
		cache = original()
		_ = r.localCache.Set(name, []byte(cache))
	} else {
		cache = string(byteCache)
	}
	return cache
}

func NewRuntimes() *Runtimes {
	instant := &Runtimes{}
	instant.localCache, _ = bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute))
	return instant
}

func (*Runtimes) GoId() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

var SelfRuntime = NewRuntimes()
